<?php

/**
 * 加载 Phalcon\Tag 函数
 */
load_functions('tag');

/**
 * 基础控制器类
 */
class ControllerBase extends \Phalcon\Mvc\Controller
{

    /**
     * 默认语言类型
     *
     * @var string
     */
    public $lang = 'zh-cn';

    /**
     * 支持的语言类型
     *
     * @var array
     */
    public $langs = null;

    /**
     * 当前 module 名称
     *
     * @var string
     */
    public $module = null;

    /**
     * 当前 controller 名称
     *
     * @var string
     */
    public $controller = null;

    /**
     * 当前 action 名称
     *
     * @var string
     */
    public $action = null;

    /**
     * Action 完成前执行
     */
    public function beforeExecuteRoute($dispatcher)
    {
        // 默认关闭 Phalcon\Tag 自动转义字符
        service('tag')->setAutoEscape(false);

        $this->lang       = $this->i18n->getDefault();
        $this->langs      = config('application.i18n.supports')->toArray();
        $this->module     = $dispatcher->getModuleName();
        $this->controller = camel($dispatcher->getControllerName(), true);
        $this->action     = $dispatcher->getActionName();

        // 要求登录
        if (! ($this->controller === 'User' &&
            in_array($this->action, array('login', 'logout', 'forget', 'reset')))) {
            $this->requireLogin();
        }

        // 自动加载语言包
        $this->i18n->import(array(
            uncamel($dispatcher->getControllerName()),
            uncamel($dispatcher->getControllerName()) . '/' . uncamel($dispatcher->getActionName()),
        ));

        // 网站标题
        $this->tag->setTitle(__('Formax OA System'));

        // 赋值到视图中
        $this->view->setVars(array(
            'lang'       => $this->lang,
            'langs'      => $this->langs,
            'module'     => $this->module,
            'controller' => $this->controller,
            'action'     => $this->action,
            'auth'       => $this->auth,
            'requireJS'  => 'empty',
        ));

        // 使用 assets-manager 管理样式
        $this->assets
            ->addCss('http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all', false)
            ->addCss(js_dir() . '/plugins/font-awesome/css/font-awesome.min.css')
            ->addCss(js_dir() . '/plugins/bootstrap/css/bootstrap.min.css')
            ->addCss('css/style-metronic.css')
            ->addCss('css/style.css')
            ->addCss('css/style-responsive.css')
            ->addCss('css/plugins.css')
            ->addCss('css/themes/default.css', true, true, array('id' => 'style_color'))
            ->addCss('css/print.css', true, true, array('media' => 'print'))
            ->addCss('css/custom.css');

        // AJAX 模式下，仅显示 action 视图
        if ($this->request->isAjax()) {
            $this->view->setRenderLevel(Phalcon\Mvc\View::LEVEL_ACTION_VIEW);
        }

        return true; // false 时停止执行
    }

    /**
     * 初始化方法
     *
     */
    public function initialize()
    {}

    /**
     * Action 完成后执行
     */
    public function afterExecuteRoute($dispatcher)
    {}

    /**
     * 页面重定向
     *
     * @param string  $location
     * @param boolean $external
     * @param integer $code
     */
    public function redirect($location, $external = false, $code = 302)
    {
        return $this->response->redirect($location, $external, $code)->sendHeaders();
    }

    /**
     * 要求用户必须登录
     */
    public function requireLogin()
    {
        // 判断是否登录
        if (! $this->auth->isLogined()) {
            return $this->redirect('user/login');
        }
    }

    /**
     * 简化 dispatcher->forward 方法，可同时指定参数
     *
     *     $this->forward(array('controller' => 'user', 'action' => 'login'), array('email' => 'my@mail.com'));
     *     $this->forward('user/login', array('email' => 'my@mail.com'));
     *
     * @param  string|array $forward
     * @param  array  $params
     */
    public function forward($forward, array $params = array())
    {
        $this->dispatcher->setParams($params);

        if (! is_array($forward)) {
            $array = explode('/', $forward);
            switch (true) {
                case count($array) === 3:
                    $forward = array(
                        'module'     => $array[0],
                        'controller' => $array[1],
                        'action'     => $array[2],
                    );
                    break;
                case count($array) === 2:
                    $forward = array(
                        'controller' => $array[0],
                        'action'     => $array[1],
                    );
                    break;
                case count($array) === 1:
                    $forward = array(
                        'controller' => $array[0],
                        'action'     => 'index',
                    );
                    break;
                default:
                    throw new Exception('Invalid forward arguments');
            }
        }

        return $this->dispatcher->forward($forward);
    }

}
